/*
	http://github.com/danpalmer/jquery.complexify.js

	This code is distributed under the WTFPL v2:
*/
(function ($) {	
	$.fn.extend({
		complexify: function(options, callback) {
			var defaults = {
				minimumChars: 8,
				strengthScaleFactor: 1
			};
			if($.isFunction(options) && !callback) {
				callback = options;
				options = {};
			}
			options = $.extend(defaults, options);

			return this.each(function () {
				$(this).keyup(function () {
					var username = $(options.username).val();
					var password = $(this).val();
					
					var level = 'Weak';
		    		var score = 0;
		    		
		    		
		    		//password too short
		    		if (password.length < 4 || (password.indexOf(username) != -1 && password.length - username.length < 4)){
		    			callback.call(this, level, score);
		    			return;
		    		}
		    		
		    		password = password.replace(username, '');

		    		//password length
		    		score += password.length * 4;
		    		score += ( $.fn.checkRepetition(1,password).length - password.length ) * 1;
		    		score += ( $.fn.checkRepetition(2,password).length - password.length ) * 1;
		    		score += ( $.fn.checkRepetition(3,password).length - password.length ) * 1;
		    		score += ( $.fn.checkRepetition(4,password).length - password.length ) * 1;
		   
		    		//password has 3 numbers
		    		if (password.match(/(.*[0-9].*[0-9].*[0-9])/)){ score += 5;}
		   
		    		//password has 2 symbols
		    		if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)){ score += 5 ;}
		   
		    		//password has Upper and Lower chars
		    		if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)){  score += 10;}
		   
		    		//password has number and chars
		    		if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)){  score += 15;}

		    		//password has number and symbol
		    		if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/)){  score += 15;}
		   
		    		//password has char and symbol
		    		if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/)){score += 15;}
		   
		    		//password is just a numbers or chars
		    		if (password.match(/^\w+$/) || password.match(/^\d+$/) ){ score -= 10;}
		   
		    		//verifying 0 < score < 100
		    		if ( score < 0 ){ score = 0;}
		    		if ( score > 100 ){ score = 100;}

		    		if (score >= 34 ){
		    			level = (score >= 68) ? 'Strong' : 'Normal';
		    		}
		    		
					callback.call(this, level, score);
				});
			});
			
		}
	});

})(jQuery);

$.fn.checkRepetition = function(pLen,str) {
	var res = "";
	for (var i=0; i<str.length ; i++ ){
		var repeated=true;
     
		for (var j=0;j < pLen && (j+i+pLen) < str.length;j++){
			repeated=repeated && (str.charAt(j+i)==str.charAt(j+i+pLen));
		}
		if (j<pLen){repeated=false;}
		if (repeated) {
			i+=pLen-1;
			repeated=false;
		} else {
			res+=str.charAt(i);
		}
	}
	return res;
};